import requests
import os

def upload_file(file_path, server_url, chunk_size=10 * 1024 * 1024, extra_params=None):
    file_name = os.path.basename(file_path)
    file_size = os.path.getsize(file_path)

    # 如果没有额外参数，初始化为空字典
    if extra_params is None:
        extra_params = {}

    with open(file_path, 'rb') as f:
        part_number = 1
        while chunk := f.read(chunk_size):
            # 设置表单字段和分片信息
            files = {
                "file": (file_name, chunk)
            }
            data = {
                "File-Name": file_name,
                "File-Size": str(file_size),
                "Part-Number": str(part_number),
                "Chunk-Size": str(len(chunk)),
                **extra_params  # 传递额外的表单字段
            }

            # 发送请求
            response = requests.post(server_url, files=files, data=data)

            # 检查响应状态
            if response.status_code == 200:
                # 解析 JSON 响应
                response_json = response.json()
                print(f"Part upload response: {response_json}")
            else:
                print(f"Failed to upload part {part_number}: {response.text}")
                return False

            part_number += 1

    print("All parts uploaded. The server will handle the merge.")
    return True

# 调用上传函数并传递额外参数
extra_params = {"lang": "en"}
upload_file("C:/Users/HP/Downloads/physicsworks.wav", "http://192.168.21.240:10098/recognition_chunk", extra_params=extra_params)
